/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.cid.jsfproducts;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;

/**
 * A lot to do here Use supplied exceptions if method should throw!!
 * @author hajo
 */
@Stateless
public class ProductJpaCtrl {

    @PersistenceContext(unitName="webshop_pu")
    private EntityManager em;

    public Product create(Product t) {
        System.out.println("Persisting : "+t.toString());
        em.persist(t);
        return t;
    }

    public void destroy(Long id) throws NonexistentEntityException {
        Product p = em.getReference(Product.class, id);
        p.getId();
        em.remove(p);

    }

    public void edit(Product t) throws NonexistentEntityException, Exception {
        try {
            em.getTransaction().begin();
            t = em.merge(t);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = t.getId();
                if (findEntity(id) == null) {
                    throw new NonexistentEntityException("The product with id "
                            + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public Product findEntity(Long id) {
        try {
            return em.find(Product.class, id);
        } finally {
            em.close();
        }
    }

    public List<Product> findEntities() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Product.class));
        return em.createQuery(cq).getResultList();
    }

    public List<Product> findEntities(int maxResults, int firstResult) {
        Query q = em.createQuery("select p from Product p", Product.class);
        List l = q.getResultList();
        int begin = (0 <= firstResult && firstResult < l.size() ? firstResult : l.size());
        int end = (firstResult + maxResults < l.size() ? firstResult + maxResults : l.size());
        return q.getResultList().subList(begin, end);
    }

    public int getEntityCount() {
        return em.createQuery("select count(p) from Product p", Integer.class).getSingleResult();
    }
    
}
